﻿// See https://aka.ms/new-console-template for more information
using System.Collections.Concurrent;



Console.WriteLine("生产者-1；消费者-2");
new ProcessItem().ProducerAndConsumer();
Console.ReadKey();

public class ProcessItem
{
    private static readonly BlockingCollection<int> allProcessItems = new BlockingCollection<int>(/*10*/);// 所有任务进程队列
    bool isfood = false;

    public ProcessItem()
    {
        Task.Factory.StartNew(() =>
        {
            Consumer();
        }, TaskCreationOptions.LongRunning);

    }

    public void ProducerAndConsumer()
    {
        // 生产
        Producer();
    }
    public void Producer()
    {
        //Task.Run(() =>
        //{
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Console.WriteLine($"生产-{i}");
                    allProcessItems.Add(i);
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine($"--------消费失败----------{i}");
                }

            }
        //});
    }

    public void Consumer()
    {
        while (!allProcessItems.IsCompleted)
        {
            try
            {
                Console.WriteLine($"--------消费----------{allProcessItems.Count()}");
                //if (allProcessItems.Count() > 0)
                //{
                    Console.WriteLine($"--------消费----------{allProcessItems.Take()}");
                //}
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine($"--------消费失败----------{e}");
            }
        }

        //while (true)
        //{
        //    // 消费者可以根据 IsCompleted 来判断是否所有的项都已被消费完毕
        //    while (allProcessItems.Count > 0 && !allProcessItems.IsCompleted)
        //    {
        //        try
        //        {
        //            Console.WriteLine($"--------消费----------{allProcessItems.Take()}");
        //        }
        //        catch (InvalidOperationException e)
        //        {
        //            Console.WriteLine($"--------消费失败----------{e}");
        //        }
        //    }
        //    //return;
        //}

        //Console.WriteLine($"没有可消费的产品");

    }
}


//BlockingCollection<int> collection = new BlockingCollection<int>();

//Console.WriteLine("生产者-1；消费者-2");

//Task.Factory.StartNew(() =>
//{
//    int i = 0;
//    while (i < 5)
//    {
//        var val = Random.Shared.Next();
//        collection.Add(val);
//        i++;
//        Console.WriteLine($"pro-total:{collection.Count}current:{val}");

//        Thread.Sleep(1500);
//    }

//});

//Task.Factory.StartNew(() =>
//{
//    while (!collection.IsCompleted)
//    {
//        Console.WriteLine($"cus- total:{collection.Count}");
//        var val = collection.Take();
//        Console.WriteLine($"cus- total:{collection.Count}current:{val}");

//    }

//}, TaskCreationOptions.LongRunning);




//Console.ReadKey();